import * as echarts from '../../../ec-canvas/echarts';
var util = require('../../../utils/util.js');
var apiObject = require('../../../utils/api.js');
var app = getApp();

Page({

  data: {
    imageHost: apiObject.imageHost,
    ec: {
      lazyLoad: true
    },
    tabs: ["农场信息", "环境调节", "环境监测", "设备管理"],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    sliderWidth: 80,

    elementArray: ['温度', '光照', 'CO2', '土壤酸碱度'],
    elementIndex: 0,


    date: "2016-09-01",
  },

  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },

  onLoad: function (e) {
    var that = this;
    this.setData({
      farmId: e.id
    })

    util.request(apiObject.api.getFarmById, {
      farmId: that.data.farmId
    }).then(function (res) {
      console.log(res)
      if (res.code == 200) {
        that.setData({
          farm: res.result.farm,
          elementStatusList: res.result.elementStatusList,
          timeElement: res.result.timeElement,
        })
      } else {
        util.showModal(res.message);
      }
    })
  },
  onShow: function(e) {
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - that.data.sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });


  },

  tabClick: function(e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
    this.init();
  },
  initEChart:function(option,echartName){
    this.selectComponent('#' + echartName).init((canvas, width, height) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      chart.setOption(option)
      return chart;
    });
  },


  init:function(){

    for(var i in this.data.timeElement){
      var data={
        title: this.data.timeElement[i].title,
        xData: this.data.timeElement[i].timeStr,
        yData: this.data.timeElement[i].value,
        minLimit: this.data.timeElement[i].minLimit,
        maxLimit: this.data.timeElement[i].maxLimit,
        min: this.data.timeElement[i].min,
        max: this.data.timeElement[i].max,
      }
      this.initEChart(util.lineEchartOption(data), "eChart" + this.data.timeElement[i].equipmentCategory)
    }
    
  },


  addFarm: function () {
    var that = this
    util.showModal("扫描设备旁的二维码获取设备信息和控制权限").then(function (res) {
      that.scanFarm();
    })
  },
  scanFarm: function () {
    wx.scanCode({
      success: function (e) {
        console.log(JSON.parse(e.result))
      }
    })
  },
  redirectToDetail:function(e){
    var id=e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../setElement/index?id='+id
    })
  }
})